package com.bwie.gateway.filters;

import com.bwie.common.constants.TokenConstants;
import com.bwie.common.utils.JwtUtils;
import com.bwie.common.utils.StringUtils;
import com.bwie.gateway.config.IgnoreWhitesConfig;
import com.bwie.gateway.utils.GatewayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @ 拦截请求 验证token
 * @descriptions: AuthFilter
 * @author: LiYang
 * @date: 2025/4/25 1:08
 * @version: 1.0
 */
@Component
public class AuthFilter implements GlobalFilter, Ordered {
    @Autowired
    private IgnoreWhitesConfig ignoreWhitesConfig;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //判断请求是否是白名单
        List<String> whites = ignoreWhitesConfig.getWhites();
        //获取请求对象
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();
        if(StringUtils.matches(path,whites)){
            //放行
            return chain.filter(exchange);
        }
        //验证token
        String token = request.getHeaders().getFirst(TokenConstants.TOKEN);
        if(StringUtils.isBlank(token)){
            return GatewayUtils.errorResponse(exchange,"token不能为空");
        }
        try {
            JwtUtils.parseToken(token);
        }catch (Exception e){
            return GatewayUtils.errorResponse(exchange,"token不合法");
        }
        String userKey = JwtUtils.getUserKey(token);
        Boolean hasKey = redisTemplate.hasKey(TokenConstants.LOGIN_TOKEN_KEY+userKey);
        if(!hasKey){
            return GatewayUtils.errorResponse(exchange,"token已过期");
        }else{
            //续期
            redisTemplate.expire(TokenConstants.LOGIN_TOKEN_KEY+userKey,30, TimeUnit.MINUTES);
        }
        return chain.filter(exchange);

    }

    @Override
    public int getOrder() {
        return 0;
    }
}
